<template>
    <div class="dsContainer">
      <div class="dsMain">
        <div class="dsIp">
          <el-upload style="margin: 10px"
              class="avatar-uploader"
              action="#"
              :show-file-list="false"
              :before-upload="beforeAvatarUpload"
              :http-request="executeUpload"
          >
            <img v-if="imageUrl" :src="imageUrl" class="avatar"/>
            <el-icon v-else class="avatar-uploader-icon">
              <Plus/>
            </el-icon>
          </el-upload>
          <el-form-item>
            <div v-for="(item, index) in prompts">
              <el-input
                  style="width: 150%; font-size: 10px"
                  :rows="3"
                  v-model="item['english']"
                  type="textarea"
                  autocomplete="off"
                  placeholder="English Prompt"
                  @input="debouncedTranslate(index, 'english')"
              />
              <el-input
                  style="width: 150%; font-size: 10px"
                  :rows="3"
                  v-model="item['chinese']"
                  type="textarea"
                  autocomplete="off"
                  placeholder="Chinese Prompt"
                  @input="debouncedTranslate(index, 'chinese')"
              />
  
            </div>
  
          </el-form-item>
        </div>
        <div class="dsIp" style="background-color: #fdc4c4">
          <el-upload style="margin: 10px"
              class="avatar-uploader"
              action="#"
              :show-file-list="false"
              :before-upload="beforeAvatarUpload"
              :http-request="executeUpload1"
          >
            <img v-if="imageUrl1" :src="imageUrl1" class="avatar"/>
            <el-icon v-else class="avatar-uploader-icon">
              <Plus/>
            </el-icon>
          </el-upload>
          <el-form-item>
            <div v-for="(item, index) in prompts1">
              <el-input
                  style="width: 150%; font-size: 10px"
                  v-model="item['english']"
                  type="textarea"
                  :rows="3"
                  autocomplete="off"
                  placeholder="English Prompt"
                  @input="debouncedTranslate1(index, 'english')"
              />
              <el-input
                  style="width: 150%; font-size: 10px"
                  v-model="item['chinese']"
                  type="textarea"
                  :rows="3"
                  autocomplete="off"
                  placeholder="Chinese Prompt"
                  @input="debouncedTranslate1(index, 'chinese')"
              />
  
            </div>
  
          </el-form-item>
        </div>
      </div>
      <div v-for="(item, index) in prompts2">
        <el-input
            class="tailMain0"
            style="width: 100%"
            v-model="item['english']"
            type="textarea"
            autocomplete="off"
            placeholder="English Prompt"
            @input="debouncedTranslate2(index, 'english')"
        />
        <el-input
            class="tailMain1"
            style="width: 100%"
            v-model="item['chinese']"
            type="textarea"
            autocomplete="off"
            placeholder="Chinese Prompt"
            @input="debouncedTranslate2(index, 'chinese')"
        />
      </div>
      <textarea ref="tailMain2" class="tailMain2">
      </textarea>
    </div>
  
  </template>
  <script lang="ts" setup>
  import {onBeforeUnmount, onMounted, onUnmounted, ref} from 'vue'
  import type {FormInstance, UploadProps} from 'element-plus'
  import {ElMessage} from 'element-plus'
  import {Plus} from '@element-plus/icons-vue'
  import axiosInstance from "@/utils/axios";
  import {MD5} from "@/utils/MD5"
  import {jsonp} from "vue-jsonp";
  import {debounce} from 'lodash';
  import {useStore} from 'vuex'; // 引入 Vuex store
  import {useRouter} from 'vue-router'; // 添加路由导入
  import callBaiduAPI from '@/utils/BaiduTrans'
  
  const router = useRouter(); // 初始化路由
  
  const imageUrl = ref('')
  const imageUrl1 = ref('')
  let prompts = ref([
    {
      'english': '',
      'chinese': '',
      'num': 0
    },
    {
      'english': '',
      'chinese': '',
      'num': 0
    },
    {
      'english': '',
      'chinese': '',
      'num': 0
    },
    {
      'english': '',
      'chinese': '',
      'num': 0
    }])
  let prompts1 = ref([
    {
      'english': '',
      'chinese': '',
      'num': 0
    },
    {
      'english': '',
      'chinese': '',
      'num': 0
    },
    {
      'english': '',
      'chinese': '',
      'num': 0
    },
    {
      'english': '',
      'chinese': '',
      'num': 0
    }])
  let prompts2 = ref([
    {
      'english': '',
      'chinese': '',
      'num': 0
    }
  ])
  
  
  const store = useStore();
  const links = ref([
    {
      'url': 'http://gips0.baidu.com/it/u=3602773692,1512483864&fm=3028&app=3028&f=JPEG&fmt=auto?w=960&h=1280',
      'index': 0
    },
    {
      'url': 'http://gips0.baidu.com/it/u=3602773692,1512483864&fm=3028&app=3028&f=JPEG&fmt=auto?w=960&h=1280',
      'index': 1
    },
    {
      'url': 'http://gips0.baidu.com/it/u=3602773692,1512483864&fm=3028&app=3028&f=JPEG&fmt=auto?w=960&h=1280',
      'index': 2
    }
  ]);
  
  const pics = ref(links.value.map(item => item.url));
  
  let intervalId = null;
  
  const fetchTaskList = async () => {
    try {
      let ids = [...store.state.imageCode.new]
      await axiosInstance.post('task/list-by-condition', {
        'ids': ids
      }).then(response => {
        for (let i = 0; i < response.data.length; i++) {
          let scopeParam = response.data[i];
          if (scopeParam.status === 'SUCCESS') {
            let index = store.state.imageCode.new.indexOf(scopeParam.id);
            if (index !== -1) {
              store.commit('appendImageCode', {
                new: [],
                old: [scopeParam.id]
              });
              store.commit('removeImageCode', {
                new: [scopeParam.id],
                old: []
              });
            }
            console.log(store.state.imageCode)
          }
        }
      }).catch(error => {
        console.error('error submit!', error);
      });
    } catch (error) {
      console.error('Error fetching task list:', error);
    }
  };
  
  onMounted(() => {
    // 恢复数据
    const savedPrompts = localStorage.getItem('prompts');
    const savedPrompts1 = localStorage.getItem('prompts1');
    const savedPrompts2 = localStorage.getItem('prompts2');
    const savedImageUrl = localStorage.getItem('imageUrl');
    const savedImageUrl1 = localStorage.getItem('imageUrl1');
    const savedTailMain2 = localStorage.getItem('tailMain2'); // 添加对 tailMain2 的恢复
  
    if (savedPrompts) prompts.value = JSON.parse(savedPrompts);
    if (savedPrompts1) prompts1.value = JSON.parse(savedPrompts1);
    if (savedPrompts2) prompts2.value = JSON.parse(savedPrompts2);
    if (savedImageUrl) imageUrl.value = savedImageUrl;
    if (savedImageUrl1) imageUrl1.value = savedImageUrl1;
    if (savedTailMain2 && tailMain2.value) tailMain2.value.value = savedTailMain2; // 恢复 tailMain2 的值
  
    if (store.state.imageCode.new.length > 0) {
      intervalId = setInterval(fetchTaskList, 2000);
    }
  
    // 添加键盘事件监听
    window.addEventListener('keydown', handleCommandEnter);
  });
  
  onUnmounted(() => {
    // 保存数据
    localStorage.setItem('prompts', JSON.stringify(prompts.value));
    localStorage.setItem('prompts1', JSON.stringify(prompts1.value));
    localStorage.setItem('prompts2', JSON.stringify(prompts2.value));
    localStorage.setItem('imageUrl', imageUrl.value);
    localStorage.setItem('imageUrl1', imageUrl1.value);
    if (tailMain2.value) localStorage.setItem('tailMain2', tailMain2.value.value); // 保存 tailMain2 的值
  
    if (intervalId) {
      clearInterval(intervalId);
    }
  
    // 移除键盘事件监听
    window.removeEventListener('keydown', handleCommandEnter);
  });
  
  async function submitDescribe(payload) {
    try {
      const response = await axiosInstance.post('/submit/describe', payload);
      console.log('upload!', response.data['result']);
      let respStatus = "";
  
      async function checkTaskStatus() {
        try {
          const taskResponse = await axiosInstance.post('/task/list-by-condition', {'ids': [response.data['result']]});
          console.log('task list!', taskResponse.data);
  
          if (taskResponse.data[0].prompt === "Unknown error") {
            alert('上传失败')
          } else if (taskResponse.data[0].status === 'SUCCESS') {
            imageUrl.value = taskResponse.data[0]['imageUrl']
            let promptData = taskResponse.data[0]['prompt']
                .replaceAll("1️⃣ ", '')
                .replaceAll("2️⃣ ", '')
                .replaceAll("3️⃣ ", '')
                .replaceAll("4️⃣ ", '')
                .split('\n\n')
            prompts.value = promptData.map((element, index) => {
              return {
                "english": element,
                "chinese": "",
                "num": 0
              }
            })
            prompts.value.forEach((prompt, index) => {
              callBaiduAPI(prompt.english, index, 'chinese')
                  .then(response => {
                    prompts.value[index]['chinese'] = response;
                  })
                  .catch(error => {
                    console.error("Error calling Baidu API:", error);
                  });
            });
            respStatus = 'SUCCESS';
          } else if (taskResponse.data[0].status === "FAILURE") {
            alert('上传失败')
          } else {
            setTimeout(checkTaskStatus, 2000);
          }
        } catch (error) {
          console.error('task list error!', error.response || error.message);
        }
      }
  
      checkTaskStatus();
  
    } catch (error) {
      console.error('error upload!', error.response || error.message);
    }
  }
  async function submitDescribe1(payload) {
    try {
      const response = await axiosInstance.post('/submit/describe', payload);
      console.log('upload!', response.data['result']);
      let respStatus = "";
  
      async function checkTaskStatus() {
        try {
          const taskResponse = await axiosInstance.post('/task/list-by-condition', {'ids': [response.data['result']]});
          console.log('task list!', taskResponse.data);
  
          if (taskResponse.data[0].prompt === "Unknown error") {
            alert('上传失败')
          } else if (taskResponse.data[0].status === 'SUCCESS') {
            imageUrl1.value = taskResponse.data[0]['imageUrl']
            let promptData = taskResponse.data[0]['prompt']
                .replaceAll("1️⃣ ", '')
                .replaceAll("2️⃣ ", '')
                .replaceAll("3️⃣ ", '')
                .replaceAll("4️⃣ ", '')
                .split('\n\n')
            prompts1.value = promptData.map((element, index) => {
              return {
                "english": element,
                "chinese": "",
                "num": 0
              }
            })
            prompts1.value.forEach((prompt, index) => {
              callBaiduAPI(prompt.english, index, 'chinese')
                  .then(response => {
                    prompts1.value[index]['chinese'] = response;
                  })
                  .catch(error => {
                    console.error("Error calling Baidu API:", error);
                  });
            });
            respStatus = 'SUCCESS';
          } else if (taskResponse.data[0].status === "FAILURE") {
            alert('上传失败')
          } else {
            setTimeout(checkTaskStatus, 2000);
          }
        } catch (error) {
          console.error('task list error!', error.response || error.message);
        }
      }
  
      checkTaskStatus();
  
    } catch (error) {
      console.error('error upload!', error.response || error.message);
    }
  }
  
  const executeUpload = (file) => {
    console.log('file', file)
    var reader = new FileReader();
    reader.readAsDataURL(file.file);
    reader.onload = () => {
      console.log("file 转 base64结果：" + reader.result);
      const payload = {
        "base64": reader.result
      };
  
      console.log('payload', payload)
  
      submitDescribe(payload)
    };
  }
  
  const executeUpload1 = (file) => {
    console.log('file', file)
    var reader = new FileReader();
    reader.readAsDataURL(file.file);
    reader.onload = () => {
      console.log("file 转 base64结果：" + reader.result);
      const payload = {
        "base64": reader.result
      };
  
      console.log('payload', payload)
  
      submitDescribe1(payload)
    };
  }
  const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
    if (rawFile.type !== 'image/jpeg' && rawFile.type !== 'image/png') { // 修改条件判断
      ElMessage.error('Avatar picture must be JPG or PNG format!')
      return false
    } else if (rawFile.size / 1024 / 1024 > 10) {
      ElMessage.error('Avatar picture size can not exceed 10MB!')
      return false
    }
    return true
  }
  
  
  
  const submitForm = (formEl: FormInstance | undefined) => {
    if (!formEl) return
    formEl.validate((valid) => {
      if (valid) {
        for (let obj of prompts.value) {
          if (obj.english === '' || obj.num < 1) {
            continue
          }
          const sendRequest = (index: number) => {
            if (index >= obj.num) return;
            const json_data = {
              'base64Array': [],
              'notifyHook': '',
              'prompt': obj.english,
              'state': '',
            }
            axiosInstance.post('/submit/imagine', json_data)
                .then(response => {
                  console.log('submit!', response.data);
                  // 将返回值放入 new 数组
                  if (response.data.result !== null) {
                    store.commit('appendImageCode', {new: [response.data.result], old: []});
  
                  }
                  setTimeout(() => sendRequest(index + 1), 3000);
                })
                .catch(error => {
                  console.error('error submit!', error);
                  setTimeout(() => sendRequest(index + 1), 3000);
                });
          };
          sendRequest(0);
        }
      } else {
        console.log('error submit!')
      }
    })
  }
  const resetForm = (formEl: FormInstance | undefined) => {
    if (!formEl) return
    formEl.resetFields()
  }
  const debouncedTranslate = debounce((index, field) => {
    const text = field === 'english' ? prompts.value[index].english : prompts.value[index].chinese;
    if (text === '') {
      return;
    }
    callBaiduAPI(text, index, field === 'english' ? 'chinese' : 'english')
        .then(response => {
          prompts.value[index][field === 'english' ? 'chinese' : 'english'] = response;
        })
        .catch(error => {
          console.error("Error calling Baidu API:", error);
        });
  }, 2000);
  const debouncedTranslate1 = debounce((index, field) => {
    const text = field === 'english' ? prompts1.value[index].english : prompts1.value[index].chinese;
    if (text === '') {
      return;
    }
    callBaiduAPI(text, index, field === 'english' ? 'chinese' : 'english')
        .then(response => {
          prompts1.value[index][field === 'english' ? 'chinese' : 'english'] = response;
        })
        .catch(error => {
          console.error("Error calling Baidu API:", error);
        });
  }, 2000);
  const debouncedTranslate2 = debounce((index, field) => {
    const text = field === 'english' ? prompts2.value[index].english : prompts2.value[index].chinese;
    if (text === '') {
      return;
    }
    callBaiduAPI(text, index, field === 'english' ? 'chinese' : 'english')
        .then(response => {
          prompts2.value[index][field === 'english' ? 'chinese' : 'english'] = response;
        })
        .catch(error => {
          console.error("Error calling Baidu API:", error);
        });
  }, 2000);
  
  const tailMain2 = ref<HTMLTextAreaElement | null>(null)
  
  const handleCommandEnter = (event: KeyboardEvent) => {
    if (event.key === 'Enter' && (event.metaKey || event.ctrlKey)) { // Command + Enter for Mac, Ctrl + Enter for Windows
      event.preventDefault()
      validateTailMain1AndTailMain2()
    }
  }
  
  const validateTailMain1AndTailMain2 = () => {
    if (prompts2.value.length > 0 && tailMain2.value) {
      const value0 = prompts2.value[0]['english'].trim(); // 假设校验第一个元素的english字段
      const value2 = tailMain2.value.value.trim();
      console.log('value0:', value0);
      console.log('value2:', value2);
  
      if (value0 === '') {
        ElMessage.error('prompts2 中的英文不能为空');
      } else if (value2 === '') {
        ElMessage.error('tailMain2 不能为空');
      } else {
        ElMessage.success('校验通过');
        localStorage.setItem('inputs', JSON.stringify([]));
  
  
        router.push({ path: '/about', query: { value0: value0 + " ", value2: value2 } }); // 添加跳转逻辑
      }
    }
  }
  
  onMounted(() => {
    window.addEventListener('keydown', handleCommandEnter)
  })
  
  onBeforeUnmount(() => {
    window.removeEventListener('keydown', handleCommandEnter)
  })
  
  </script>
  
  
  <style scoped>
  .dsContainer {
    display: flex;
    flex-direction: column;
    height: 100vh; /* 视口高度 */
  }
  .avatar-uploader .avatar {
    width: 100px;
    height: 100px;
    display: block;
  }
  .dsMain {
    flex: 6;
    width: 100%;
    height: 100vh;
    display: flex;
    background-color: #fdc4c4;
  }
  .dsMain, .tailMain0, .tailMain1, .tailMain2 {
    text-align: center;
    font-size: 10px;
    align-items: center;
    justify-content: center;
  }
  .tailMain0 {
    flex: 1;
    background-color: #e9ffed;
  }
  
  .tailMain1 {
    flex: 1;
    background-color: #e9fffa;
  }
  
  .tailMain2 {
    flex: 0.5;
    background-color: #ffecec;
  }
  .dsIp {
    width: 50%;
    height: 100%;
    background-color: #fdfc4c;
    display: flex;
    justify-content: center;
  }
  
  
  
  .avatar-uploader .el-upload {
    border: 1px dashed var(--el-border-color);
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: var(--el-transition-duration-fast);
  }
  
  .avatar-uploader .el-upload:hover {
    border-color: var(--el-color-primary);
  }
  
  .el-icon.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 100px;
    height: 100px;
    text-align: center;
  }
  
  .slider-demo-block .el-slider {
    margin-top: 0;
  }
  
  .slider-demo-block .demonstration {
    font-size: 14px;
    color: var(--el-text-color-secondary);
    line-height: 20px;
    flex: 1;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
    margin-bottom: 0;
  }
  
  .slider-demo-block .demonstration + .el-slider {
    flex: 0 0 95%;
  }
  
  .picLable {
    margin: 20px;
  }
  
  .demo-image__error .image-slot {
    font-size: 30px;
  }
  
  .demo-image__error .image-slot .el-icon {
    font-size: 30px;
  }
  
  .demo-image__error .el-image {
    width: 100%;
    height: 200px;
  }
  </style>